<?php

class NucleosbasicosController extends GxController {
private $redireccion = "edit";
    public function filters() {
        return array(
            'accessControl',
        );
    }

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index', 'view'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('minicreate','carga', 'create', 'update', 'guardarnucleo', 'autocomplete', 'cargar_lista', 'ordenarlistas', 'cargar_alias', 'eliminarnucleo'),
                'users' => array('@'),
            ),
            array('allow',
                'actions' => array('admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

    public function actionView($id) {
        Controller::registrar_scrips();
        $this->render('view', array(
            'model' => $this->loadModel($id, 'Nucleosbasicos'),
        ));
    }

    public function actionCreate($para = null) {
        Controller::registrar_scrips();
        Controller::registrar_scrips_jquery();
        if ($para == 1){
            $this->redireccion = "view";
            $this->layout = '//layouts/column3';
        }
        $model = new Nucleosbasicos;
        $this->performAjaxValidation($model, 'nucleosbasicos-form');

        if (isset($_POST['Nucleosbasicos'])) {
            $model->setAttributes($_POST['Nucleosbasicos']);

            if ($model->save()) {
                if (Yii::app()->getRequest()->getIsAjaxRequest())
                    Yii::app()->end();
                else
                    $this->redirect(array('view', 'id' => $model->NCLBID));
            }
        }

        $this->render('create', array('model' => $model));
    }

    public function actionCarga() {
        $connection = Yii::app()->db;
        $command = $connection->createCommand("select NCLBID, NCLBNOMBRE FROM NUCLEOSBASICOS ORDER BY NCLBNOMBRE");
        $results = $command->queryAll();
        $campo = "<option value=''>Seleccione...</option>";
        foreach ($results as $rows) {
            $valor = array_values($rows);
            $campo .="<option value='$valor[0]'>$valor[1]</option>";
        }
        echo $campo;
    }
    public function actionUpdate($id) {
        $model = $this->loadModel($id, 'Nucleosbasicos');

        $this->performAjaxValidation($model, 'nucleosbasicos-form');
        Controller::registrar_scrips();
        $baseUrl = Yii::app()->baseUrl;
        $cs = Yii::app()->getClientScript();
        $cs->registerScriptFile($baseUrl . '/js/nucleo_basico.js');
        if (isset($_POST['Nucleosbasicos'])) {
            $model->setAttributes($_POST['Nucleosbasicos']);

            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->NCLBID));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionDelete($id) {
        Controller::registrar_scrips();
        if (Yii::app()->getRequest()->getIsPostRequest()) {
            $this->loadModel($id, 'Nucleosbasicos')->delete();

            if (!Yii::app()->getRequest()->getIsAjaxRequest())
                $this->redirect(array('admin'));
        } else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionIndex() {
        Controller::registrar_scrips();
        $dataProvider = new CActiveDataProvider('Nucleosbasicos');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function actionAdmin() {
        Controller::registrar_scrips();
        $model = new Nucleosbasicos('search');
        $model->unsetAttributes();

        if (isset($_GET['Nucleosbasicos']))
            $model->setAttributes($_GET['Nucleosbasicos']);

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function actionAutocomplete() {
        if (isset($_GET['term'])) {
            $proveedores = Yii::app()->db->createCommand("SELECT ALSID, ALSNOMBRE FROM ALIAS WHERE ALSNOMBRE LIKE '%" . $_GET['term'] . "%' AND ROWNUM < 30")->queryAll();
            $return_array = array();
            foreach ($proveedores as $proveedor) {
                $valor = array_values($proveedor);
                $return_array[] = array(
                    'label' => $valor[1],
                    'value' => $valor[0],
                );
            }
            echo CJSON::encode($return_array);
        }
    }

    public function actionCargar_lista($modulo, $nucleo) {
        $sql = "SELECT ALSID, ALSNOMBRE, b.ORDEN FROM ALIAS a JOIN NUCLEOSBASICOSALIAS b ON a.ALSID=b.ALS_ID WHERE b.MOD_ID=$modulo AND b.NCLB_ID = $nucleo ORDER BY ORDEN";
        $connection = Yii::app()->db;
        $command = $connection->createCommand($sql);
        $results = $command->queryAll();
        foreach ($results as $rows) {
            $valor = array_values($rows);
            echo '<div class="portlet ui-state-default ui-widget ui-widget-content ui-helper-clearfix ui-corner-all alias-disponibles-opt" lisid="' . $valor[0] . '" lisorden="' . $valor[2] . '" ><div class="portlet-header ui-widget-header ui-corner-all"><span class="ui-icon ui-icon-closethick" onclick="eliminar(this);"></span><span class="ui-icon ui-icon-plusthick" onclick="potlet(this);"></span>' . substr($valor[1], 0, 60) . '...</div> <div class="portlet-content">' . $valor[1] . '</div></div>' . "\n";
        }
    }

    public function actionOrdenarlistas($arreglo, $modulo, $nucleo) {
        $qry = "";
        $rowsafect = 0;
        if (Yii::app()->browser->getBrowser() == "Internet Explorer")
            $rows = explode(";", trim(utf8_encode($arreglo), ';'));
        else
            $rows = explode(";", trim($arreglo, ';'));

        $connection = Yii::app()->db;
        foreach ($rows as $results) {
            $cells = explode(",", $results);
            $qry = "UPDATE NUCLEOSBASICOSALIAS SET ORDEN=$cells[2] WHERE ALS_ID=$cells[0] AND MOD_ID=$modulo AND NCLB_ID = $nucleo";
            try {
                $command = $connection->createCommand($qry);
                $rowCount = $command->execute();
                if ($rowCount > 0) {
                    $rowsafect = $rowsafect + $rowCount;
                }
            } catch (Exception $e) {
                echo $e;
            }
        }
        echo "Ordenados correctamente";
    }

    public function actionGuardarnucleo($alias, $modulo, $nucleo) {
        $connection = Yii::app()->db;
        $order = $connection->createCommand("SELECT MAX(ORDEN) + 1 FROM NUCLEOSBASICOSALIAS WHERE NCLB_ID=$nucleo AND MOD_ID=$modulo")->queryScalar();
        if (!is_numeric($order))
            $order = 0;

        $qry = "INSERT INTO NUCLEOSBASICOSALIAS ( ALS_ID, NCLB_ID, MOD_ID, ORDEN ) VALUES ($alias, $nucleo, $modulo, $order )";
        try {
            $command = $connection->createCommand($qry);
            $rowCount = $command->execute();
        } catch (Exception $e) {  //an exception is raised if a query fails
            echo $e;
        }
        if ($rowCount > 0)
            echo "true";
    }

    public function actionCargar_alias($nucleo) {
        $campo = "<option value=''></option>";
        $connection = Yii::app()->db;
        $command = $connection->createCommand("SELECT ALSID, ALSNOMBRE FROM ALIAS WHERE ALSID NOT IN (SELECT ALS_ID FROM NUCLEOSBASICOSALIAS WHERE NCLB_ID=$nucleo) ORDER BY ALSNOMBRE");
        $results = $command->queryAll();
        foreach ($results as $rows) {
            $valor = array_values($rows);
            $campo .="<option value='$valor[0]'>$valor[1]</option>";
        }
        echo $campo;
    }

    public function actionEliminarnucleo($alias, $modulo, $nucleo) {
        $connection = Yii::app()->db;
        $qry = "DELETE FROM NUCLEOSBASICOSALIAS WHERE NCLB_ID=$nucleo AND MOD_ID=$modulo AND ALS_ID=$alias";
        try {
            $command = $connection->createCommand($qry);
            $rowCount = $command->execute();
        } catch (Exception $e) {  //an exception is raised if a query fails
            echo $e;
        }
        if ($rowCount > 0)
            echo "true";
    }

}